package com.inspur.gs.sbssdl.sbssgl.sbtz.sbtz.back.sbsssbtz.common;

import com.inspur.edp.svc.document.storage.api.DocStorageService;
import com.inspur.edp.svc.document.storage.entity.GspDocMetadata;
import com.inspur.edp.svc.document.storage.entity.GspDocOperatingModes;
import com.inspur.gs.sbssdl.sbssgl.sbtz.sbtz.back.util.QRUtil;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.client.RpcClassHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;

public class SbssSbtzQrImageUtil {
    private String rootId = "sbqr-root";

    public QrMetaData updQRCode(String sbbh) {
        Resource resource = new ClassPathResource("");
        String toRemove = "server" + File.separator + "runtime" + File.separator + "3rd";
        try {
            String rootPath = resource.getFile().getAbsolutePath().replace(toRemove, "");
            if (sbbh != null && !StringUtils.isBlank(sbbh)){
                String fileName = sbbh + ".png";
                Path pngPath = Paths.get(rootPath, "web", "apps", "sbssdl", rootId);
                Files.createDirectories(pngPath);

                QRUtil qrUtil = new QRUtil();
                String sbbhsPath = qrUtil.generateQRCode(fileName, pngPath.toString(), 300, 300);
                byte[] sbbhs = Files.readAllBytes(Paths.get(sbbhsPath));

                // 上传到服务器
                RpcClassHolder rpcClassHolder = SpringBeanUtils.getBean(RpcClassHolder.class);
                DocStorageService docStorage = rpcClassHolder.getRpcClass(DocStorageService.class);

                GspDocMetadata metadata = new GspDocMetadata(rootId);
                metadata.setFileName(fileName + ".png");
                metadata.setDocType("png");
                metadata.setDocSize(String.valueOf(sbbhs.length));
                // 上传
                String attId = docStorage.uploadDoc(fileName, metadata, sbbhs, GspDocOperatingModes.Formal);

                QrMetaData qrMetaData = new QrMetaData();
                qrMetaData.setMetadata(metadata);
                qrMetaData.setAttachmentId(attId);
                return qrMetaData;
            }
        }catch (IOException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
